package com.dream.keigezhushou.Activity.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dream.keigezhushou.Activity.bean.GoodsBean;
import com.dream.keigezhushou.Activity.bean.Image;
import com.dream.keigezhushou.Activity.bean.StoreBean;
import com.dream.keigezhushou.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 *  创建ExpandableListView的适配器
 */

public class MyExpandableListAdapter extends BaseExpandableListAdapter{

    private Context mContext;

    //父item的集合
    private List<Map<String,Object>>  parentList;

    //子item的集合
    private List<List<Map<String,Object>>> childList;

    //新的价格
    double newPrice = 0.00;
    //旧价格
    double oldPrice = 0.00;
    //总价
    double totalPrice = 0.00;
    //商品价格
    double proPrice = 0.00;
    //商品数量
    int productCount = 0;
    //购买总数
    int totalCount = 0;

    //购物车的两中状态  编辑与完成
    public static final String EDITING = "编辑";
    public static final String FINISH_EDITING = "完成";

    OnAllCheckedBoxNeedChangeListener onAllCheckedBoxNeedChangeListener;
    OnGoodsCheckedChangeListener onGoodsCheckedChangeListener;
    OnCheckHasGoodsListener onCheckHasGoodsListener;

//    public MyExpandableListAdapter(Context context) {
//
//        //初始化父、子组列表项
//
//    }

    public void setOnCheckHasGoodsListener(OnCheckHasGoodsListener onCheckHasGoodsListener) {
        this.onCheckHasGoodsListener = onCheckHasGoodsListener;
    }

    public void setOnEditingTvChangeListener(OnEditingTvChangeListener onEditingTvChangeListener) {
        this.onEditingTvChangeListener = onEditingTvChangeListener;
    }

    OnEditingTvChangeListener onEditingTvChangeListener;

    public void setOnGoodsCheckedChangeListener(OnGoodsCheckedChangeListener onGoodsCheckedChangeListener) {
        this.onGoodsCheckedChangeListener = onGoodsCheckedChangeListener;
    }

    public void setOnAllCheckedBoxNeedChangeListener(OnAllCheckedBoxNeedChangeListener onAllCheckedBoxNeedChangeListener) {
        this.onAllCheckedBoxNeedChangeListener = onAllCheckedBoxNeedChangeListener;
    }

    public MyExpandableListAdapter(Context context,List<Map<String,Object>> parentList,List<List<Map<String,Object>>> childList) {

        this.mContext = context;
        this.parentList = parentList;
        this.childList = childList;
    }


    //获取当前父item的数量
    @Override
    public int getGroupCount() {
        return parentList.size();
    }

    //获取当前父item中子的数量
    @Override
    public int getChildrenCount(int i) {
        
        return childList.get(i).size();
    }

    //获取当前父item的数据
    @Override
    public Object getGroup(int i) {
        return parentList.get(i);
    }

    //获取当前子item需要关联的数据
    @Override
    public Object getChild(int i, int i1) {
        return childList.get(i).get(i1);
    }

    //获取父item的ID
    @Override
    public long getGroupId(int i) {
        return i;
    }

    //获取子item的ID
    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    //获取到父item的组件
    @Override
    public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {

        ParentViewHolder parentHolder = null;
        if (view == null){
            view = LayoutInflater.from(mContext).inflate(R.layout.layout_parent_list_item,null);
            parentHolder = new ParentViewHolder();

            parentHolder.tvShopName = (TextView)view.findViewById(R.id.shop_place);
            parentHolder.tvEdit = (TextView)view.findViewById(R.id.edit_car);
            parentHolder.cbParent = (CheckBox)view.findViewById(R.id.check_bar);

            view.setTag(parentHolder);
        }else {
            parentHolder = (ParentViewHolder) view.getTag();
        }

        StoreBean storeBean = (StoreBean)parentList.get(i).get("parentName");
        final String parentName = storeBean.getStoreName();   //获取到商店的名称
        parentHolder.tvShopName.setText(parentName);    //设置商店的名称

        //首先判断商品是否处于编辑状态
        if (storeBean.isEditing()){

            parentHolder.tvEdit.setText(FINISH_EDITING);
        }else {
            parentHolder.tvEdit.setText(EDITING);
        }

        //编辑的点击监听
        parentHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String text = "";
                TextView textView = null;
                if (view instanceof TextView){

                    textView = (TextView) view;
                }

                textView.setText(text);
                setupEditing(i);

                onEditingTvChangeListener.onEditingTvChange(dealAllEditingIsEditing());
            }
        });
        parentHolder.cbParent.setChecked(storeBean.isChecked());
        final boolean nowChecked = storeBean.isChecked();
        //父组件的CheckBox的点击事件的监听
        parentHolder.cbParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setOneParentChecked(!nowChecked,i);
                onAllCheckedBoxNeedChangeListener.onCheckedBoxNeedChange(dealAllParentIsChecked());
            }
        });
        return view;
    }

    //获取到子item的组件
    @Override
    public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {

        ChildViewHolder childHolder = null;
        if (view == null){

            view = LayoutInflater.from(mContext).inflate(R.layout.layout_child_list_item,null);
            childHolder = new ChildViewHolder();

            //常规下的子item
            childHolder.llNormalCar = (LinearLayout)view.findViewById(R.id.ll_normal_car);
            childHolder.ivShopLogo = (ImageView)view.findViewById(R.id.iv_product);
            childHolder.tvShop = (TextView)view.findViewById(R.id.tv_shop_name);
            childHolder.tvNewPrice = (TextView)view.findViewById(R.id.tv_new_price);
            childHolder.tvOldPrice = (TextView)view.findViewById(R.id.tv_old_price);
            childHolder.tvProNum = (TextView)view.findViewById(R.id.tv_product_num);

            //编辑下的子item
            childHolder.llEditCar = (LinearLayout)view.findViewById(R.id.ll_edit_car);
            childHolder.tvEditNum = (TextView)view.findViewById(R.id.tv_number);
            childHolder.tvDelete = (TextView)view.findViewById(R.id.tv_delete);
            childHolder.rlPlus = (RelativeLayout) view.findViewById(R.id.rl_plus);
            childHolder.rlAdd = (RelativeLayout) view.findViewById(R.id.rl_add);

            childHolder.cbChild = (CheckBox)view.findViewById(R.id.check_pro);

            view.setTag(childHolder);
        }else{
            childHolder = (ChildViewHolder)view.getTag();
        }

        final GoodsBean goodsBean = (GoodsBean) childList.get(i).get(i1).get("childName");

        childHolder.tvShop.setText(goodsBean.getGoodsName());
        childHolder.tvOldPrice.setText(String.format("￥",goodsBean.getGoodsOldPrice()));
        childHolder.tvOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); //在旧价格上划中线并抗锯齿
        childHolder.tvNewPrice.setText(String.format("￥",goodsBean.getGoodsPrice())); //商品的价格
        childHolder.tvProNum.setText(String.format("x",goodsBean.getGoodsNum())); //商品的数量

        childHolder.tvEditNum.setText(String.valueOf(goodsBean.getGoodsNum())); //编辑下的商品数量
        childHolder.cbChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //点击的时候先判断当前的选中状态，如果为选中，点击之后则为不选中；反之亦然
                boolean nowBeanChecked = goodsBean.isChecked();
                //更新子组件的状态
                goodsBean.setChecked(!nowBeanChecked);

                //判断子组件的父组件的选中状态
                boolean oneParentIsChecked = dealOneParentAllChildIsChecked(i);

                StoreBean storeBean = (StoreBean)parentList.get(i);
                storeBean.setChecked(oneParentIsChecked);

                //刷新UI
                notifyDataSetChanged();
                onAllCheckedBoxNeedChangeListener.onCheckedBoxNeedChange(dealAllParentIsChecked());

                //刷新结算的价格
                dealPrice();

            }
        });

        //判断子控件的状态，显示不同的效果
        if (goodsBean.isEditing()){

            childHolder.llNormalCar.setVisibility(View.GONE);
            childHolder.llEditCar.setVisibility(View.VISIBLE);
        }else {

            childHolder.llNormalCar.setVisibility(View.VISIBLE);
            childHolder.llEditCar.setVisibility(View.GONE);
        }

        childHolder.rlPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //减少商品的数量
                dealReduce(goodsBean);
            }
        });

        childHolder.rlAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //添加商品的数量
                dealAdd(goodsBean);
            }
        });

        childHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //编辑状态下删除商品
                removeOneGood(i,i1);
            }
        });

        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }


    //供全选CheckBox的调用
    public void setAllCheck(boolean isChecked){

        /**
         *  设置所有的父组件和子组件为选中状态
         */
        for (int i = 0; i < parentList.size(); i++ ){

            StoreBean storeBean = (StoreBean) parentList.get(i).get("parentName");
            storeBean.setChecked(isChecked);

            //父组件中的所有子组件
            List<Map<String,Object>> childMapList = childList.get(i);
            for (int j = 0; j < childMapList.size(); j++){

                GoodsBean goodsBean = (GoodsBean)childMapList.get(j).get("childName");
                goodsBean.setChecked(isChecked);
            }
        }

        //刷新页面
        notifyDataSetChanged();
        //总价发生变化
        dealPrice();
    }

    //供某个父组件点击所在这个父组件下的子组件为全部选中
    public void  setOneParentChecked(boolean isChecked,int groupPosition){

        StoreBean storeBean = (StoreBean) parentList.get(groupPosition);
        storeBean.setChecked(isChecked);

        //遍历这个父组件下的子组件
        List<Map<String,Object>> oneParentChildList = childList.get(groupPosition);
        for (int j = 0; j < oneParentChildList.size(); j++){

            GoodsBean goodsBean = (GoodsBean)oneParentChildList.get(j);
            goodsBean.setChecked(isChecked);
        }

        //刷新页面
        notifyDataSetChanged();
        //总价发生变化
        dealPrice();
    }

    //供全选之后，所有的父组件以及父组件中的子组件的选中与否发生变化
    public boolean dealAllParentIsChecked(){

        /**
         *  判断父组件中的所有字组件的选中的状态是否发生变化，全部发生变化返回true，反之返回false
         */

        for (int j = 0; j < parentList.size(); j++){

            StoreBean stroeBean = (StoreBean) parentList.get(j);
            if (!stroeBean.isChecked()){
                return false;
            }
        }
        return true;
    }


    //供某个父组件选中，父组件中的子组件的选中与否发生变化
    public boolean dealOneParentAllChildIsChecked(int groupPosition){

        //父组件中的所有子组件
        List<Map<String,Object>> childMapList = childList.get(groupPosition);
        //遍历父组件中的子组件
        for (int j = 0; j < childMapList.size(); j++ ){

            GoodsBean goodsBean = (GoodsBean)childMapList.get(j);
            if (!goodsBean.isChecked()){

                return false; //如果父组件中有一个没有选中，返回false；
            }
        }

        return true;
    }


    //刷新价格的回调方法
    public void dealPrice(){

        //初始的数量和价格
        totalCount = 0;
        totalPrice = 0.00;
        //遍历父组件
        for (int i = 0; i <parentList.size(); i++){

            //父组件中的子组件
            List<Map<String,Object>> childMapList = childList.get(i);
            //遍历父组件中子组件
            for (int j = 0; j < childMapList.size(); j++){

                GoodsBean goodsBean = (GoodsBean)childMapList.get(j);

                int count = goodsBean.getGoodsNum();
                double price = goodsBean.getGoodsPrice();
                if (goodsBean.isChecked()){

                    totalCount++;//单品的数量加1
                    totalPrice += price * count;
                }
            }
        }

        onGoodsCheckedChangeListener.onGoodsCheckedChange(totalCount,totalPrice);
    }


    //供总编辑按钮调用
    public void setupEditingAll(boolean isEditingAll) {
        for (int i = 0; i < parentList.size(); i++) {
            StoreBean storeBean = (StoreBean) parentList.get(i).get("parentName");
            storeBean.setEditing(isEditingAll);

            List<Map<String, Object>> childMapList = childList.get(i);
            for (int j = 0; j < childMapList.size(); j++) {
                GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
                goodsBean.setEditing(isEditingAll);
            }
        }
        notifyDataSetChanged();
    }


    public boolean dealAllEditingIsEditing() {
        for (int i = 0; i < parentList.size(); i++) {
            StoreBean storeBean = (StoreBean) parentList.get(i).get("parentName");
            if (storeBean.isEditing()) {//!!!
                return true;//如果有一个是编辑状态  就true
            }
        }
        return false;
    }

    //编辑回调的方法
    public void setupEditing(int groupPosition) {
        StoreBean storeBean = (StoreBean) parentList.get(groupPosition).get("parentName");
        boolean isEditing = !storeBean.isEditing();
        storeBean.setEditing(isEditing);
        List<Map<String, Object>> childMapList = childList.get(groupPosition);
        for (int j = 0; j < childMapList.size(); j++) {
            GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
            goodsBean.setEditing(isEditing);
        }
        notifyDataSetChanged();
    }


    //商品数量增加的方法
    public void  dealAdd(GoodsBean goodsBean){

        int count = goodsBean.getGoodsNum();
        count++;
        goodsBean.setGoodsNum(count);
        //刷新UI
        notifyDataSetChanged();
        //价格变化
        dealPrice();
    }

    //商品数量减少的方法
    public void dealReduce(GoodsBean goodsBean){

        int count = goodsBean.getGoodsNum();
        //数量最小为1，当数量为1后，不可再进行减少
        if (count == 1){

            return;
        }

        count--;
        goodsBean.setGoodsNum(count);
        //刷新UI
        notifyDataSetChanged();
        //价格变化
        dealPrice();
    }

    // 删除某个父组件中的某个子组件
    public void removeOneGood(int groupPosition, int childPosition) {
        //StoreBean storeBean = (StoreBean) parentMapList.get(groupPosition).get("parentName");
        List<Map<String, Object>> childMapList = childList.get(groupPosition);
        // GoodsBean goodsBean = (GoodsBean) childMapList.get(childPosition).get("childName");
        childMapList.remove(childPosition);

        //通过子项
        if (childMapList!=null&&childMapList.size()>0){

        }else {
            parentList.remove(groupPosition);
            childList.remove(groupPosition);//！！！！因为parentMapList和childMapList_list是pos关联的  得保持一致
        }
        if (parentList != null && parentList.size() > 0) {
            onCheckHasGoodsListener.onCheckHasGoods(true);//
        } else {
            onCheckHasGoodsListener.onCheckHasGoods(false);//
        }

        //刷新UI
        notifyDataSetChanged();
        //刷新价格
        dealPrice();
    }


    public void removeGoods() {
    /*    for (int i = 0; i <parentMapList.size(); i++) {
            StoreBean storeBean= (StoreBean) parentMapList.get(i).get("parentName");

                List<Map<String, Object>> childMapList = childMapList_list.get(i);
                for (int j = 0; j < childMapList.size(); j++) {
                    GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
                    Log.d(TAG, "removeGoods:============goodsBean:" + goodsBean.isChecked());
                    if (goodsBean.isChecked()) {
                        childMapList.remove(j);
                        j--;//!!!!!!!!!!  List remove方法比较特殊 每移除一个元素以后再把pos移回来
                    }
                }
        }*/

        for (int i = parentList.size()-1; i>=0; i--) {//倒过来遍历  remove
            StoreBean storeBean= (StoreBean) parentList.get(i).get("parentName");
            if (storeBean.isChecked()){
                parentList.remove(i);
                childList.remove(i);
            }else {
                List<Map<String, Object>> childMapList = childList.get(i);
                for (int j = childMapList.size()-1; j >=0; j--) {//倒过来遍历  remove
                    GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
                    if (goodsBean.isChecked()) {
                        childMapList.remove(j);
                    }
                }
            }

        }
        // showList("begin###############");
        /**1.不要边遍历边删除，容易出现数组越界的情况<br>
         * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除*/  //还是有问题
        /*List<Map<String, Object>> needRemoreParentMapList = new ArrayList<>();// 待删除的组元素列表
        List<List<Map<String, Object>>> needRemoreChildMapList_List = new ArrayList<>();// 待删除的  最大的

        for (int i = 0; i < parentMapList.size(); i++) {
            StoreBean storeBean = (StoreBean) parentMapList.get(i).get("parentName");

            if(storeBean.isChecked()){
                needRemoreParentMapList.add(parentMapList.get(i));
                needRemoreChildMapList_List.add(childMapList_list.get(i));//！！！！因为parentMapList和childMapList_list是pos关联的  得保持一致
            }
                //
                List<Map<String, Object>> childMapList = childMapList_list.get(i);//最大的

                List<Map<String, Object>> needRemoreChildMapList = new ArrayList<>();// 待删除的子元素列表

                for (int j = 0; j < childMapList.size(); j++) {
                    GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
                    if (goodsBean.isChecked()) {
                        needRemoreChildMapList.add(childMapList.get(j));
                    }
                }

                childMapList.removeAll(needRemoreChildMapList);//正式删除子元素  不是childMapList_list  ！！！

        }
        parentMapList.removeAll(needRemoreParentMapList);//正式删除父元素
        Log.d(TAG, "removeGoods: needRemoreChildMapList_List"+needRemoreChildMapList_List);
        childMapList_list.remove(needRemoreChildMapList_List);//！！！！因为parentMapList和childMapList_list是pos关联的  得保持一致
*/
        //!!!!!!!!!!!!!!!删除完 状态需要重置
        resetViewAfterDelete();
        if (parentList != null && childList.size() > 0) {
            onCheckHasGoodsListener.onCheckHasGoods(true);//
        } else {
            onCheckHasGoodsListener.onCheckHasGoods(false);//
        }
        //showList("after@@@@@@@@@@@@@@@@@@@@@@@");
        notifyDataSetChanged();//
        dealPrice();//重新计算
    }

    private void resetViewAfterDelete() {
        for (int i = 0; i < parentList.size(); i++) {
            StoreBean storeBean = (StoreBean) parentList.get(i).get("parentName");
            storeBean.setChecked(false);
            storeBean.setEditing(false);
            List<Map<String, Object>> childMapList = childList.get(i);

            for (int j = 0; j < childMapList.size(); j++) {
                GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
                goodsBean.setChecked(false);
                goodsBean.setEditing(false);
            }
        }
    }

    void showList(String tempStr) {
//        Log.d(TAG, "showList:"+tempStr);
        for (int i = 0; i < parentList.size(); i++) {
            StoreBean storeBean = (StoreBean) parentList.get(i).get("parentName");
//            Log.d(TAG, "showList:  parentName:【" + storeBean.getName()+"】isChecked:" + storeBean.isChecked());
            List<Map<String, Object>> childMapList = childList.get(i);
            for (int j = 0; j < childMapList.size(); j++) {
                GoodsBean goodsBean = (GoodsBean) childMapList.get(j).get("childName");
//                Log.d(TAG, "showList:  childName:" + goodsBean.getName()+"isChecked:" + goodsBean.isChecked());
            }
        }
    }

    /**
     *
     * 某个父组件中所有子组件选中状态改变的监听接口
     */

    public interface OnAllCheckedBoxNeedChangeListener {
        void onCheckedBoxNeedChange(boolean allParentIsChecked);
    }

    /**
     *
     *  编辑的监听
     */
    public interface OnEditingTvChangeListener {
        void onEditingTvChange(boolean allIsEditing);
    }

    /**
     *  结算的监听，改变的是最后结算的数量和价格
     */
    public interface OnGoodsCheckedChangeListener {
        void onGoodsCheckedChange(int totalCount, double totalPrice);
    }

    /**
     *
     *  购物车有无商品的监听
     */
    public interface OnCheckHasGoodsListener {
        void onCheckHasGoods(boolean isHasGoods);
    }

    class ParentViewHolder{

        TextView tvShopName,tvEdit;
        CheckBox cbParent;
    }

    class ChildViewHolder{

        TextView tvShop,tvNewPrice,tvOldPrice,tvProNum,tvEditNum,tvDelete;
        RelativeLayout rlPlus,rlAdd;
        LinearLayout llNormalCar,llEditCar;
        ImageView ivShopLogo;
        CheckBox cbChild;
    }



}
